<script setup>
import {reactive, ref, watch} from 'vue'

const sumprice = ref(0)

const data = reactive([])

const goodlist = reactive([
  {name: '华为手机', price: 999, num: 1000},
  {name: '华为手表', price: 100, num: 1000},
  {name: '小米手机', price: 909, num: 3000},
  {name: '联想笔记本', price: 1999, num: 1000},
])


watch(data, async () => {
  sumprice.value = 0

  let dd = data.filter(item => item.num > 0)
  data.splice(0, data.length)
  data.push(...dd)

  data.forEach(item => {
    sumprice.value += item.price * item.num
  })
}, {immediate: true})

function add(item) {
  let {name, price} = item
  item.num--
  let g = {name, price, num: 1}
  data.push(g)
}

</script>

<template>
  <h3>商城购物车({{ data.length }})</h3>
  <template v-if="data.length>0">
    <template v-for="(goods,index) in data">
      <p>商品名称：{{ goods.name }}</p>
      <p>价格：￥<strong style="color:red">{{ goods.price }}</strong></p>
      <p>
        <button @click="goods.num--">-</button>
        <label><input type="text" readonly :value="goods.num"></label>
        <button @click="goods.num++">+</button>
      </p>
      <br>
    </template>
  </template>

  <h3>购物车总金额：{{ sumprice }}元</h3>
  <hr>
  <p v-for="(item,index) in goodlist">
    {{ item.name }} 价格：{{ item.price }} {{ item.num }}
    <button @click="add(item)">添加购物车</button>
  </p>

</template>

<style>
button {
  padding: 2px;
  min-width: 20px;
}

label {
  margin: 0 5px
}

label > input {
  padding: 3px;
  width: 30px;
  text-align: center;
  border: 0;
  border-bottom: 1px solid gray;
}
</style>

